<?php

namespace app\admin\controller;


use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;

/**
 * 优惠卷
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * Coupon模型对象
     * @var \app\common\model\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Coupon;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 发放优惠券
     * @Author Ixiangang
     * @DateTime 2024-05-30
     * @return void
     */
    public function grant($id = null)
    {
        $coupon = $this->model->where('id', $id)->find();
        $coupon['status_name'] = $coupon->status == 1 ? '满减卷' : '';
        $this->view->assign("row", $coupon);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $coupon = $this->model->where('id', $params['id'])->find();
            $day = $coupon['day'];
            for ($i = 0; $i < $params['num']; $i++) {
                $data = [
                    'coupon_id' => $params['id'],
                    'user_id' => $params['user_id'],
                    'use_for' => 1,
                    'upstage' => 1, //代表后台发放
                    'issuance_time' => time(),  //发放时间
                    'expiration' => strtotime("+$day days", time()), //根据有优惠券天数算优惠券到期时间
                    'status' => $coupon['status'],
                    'coupon_price' => $coupon['fullminus'],
                    'man_price' => $coupon['satisfynum'],
                    'createtime' => time(),
                ];
                \app\common\model\Couponlog::create($data);
            }
            $this->success("发放成功");
        }
        return $this->view->fetch();
    }


    /**
     * 获取用户信息
     * @Author Ixiangang
     * @DateTime 2024-05-30
     * @return void
     */
    public function getUserList()
    {
        if ($this->request->isPost()) {
            $name = $this->request->post('username');
            if ($name) {
                $where['nickname'] = ['like', '%' . $name . '%'];
            }
            $where['status'] = 'normal';
            $where['persona'] = '1'; //普通用户
            $list = User::field(['id', 'nickname'])->where($where)->select();
            return json(['list' => $list, 'total' => count($list)]);
        }
    }


    /**
     * 全部发放优惠券
     * @Author Ixiangang
     * @DateTime 2024-05-30
     * @param [type] $ids
     * @return void
     */
    public function grantall($ids = null){
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('id','=',$ids)->find();
            if (!$list) {
                $this->error(__('数据不存在'));
            }
            $params = [];
            Db::startTrans();
            try {
                # 查询优惠券
                $coupon = $this->model->where('id', $ids)->find();
                # 开始全部用户发放优惠券
                $list = User::field(['id', 'nickname'])->where(['status' =>'normal','persona' => 1 ])->select();
                $data = [];
                $day = $coupon['day'];
                $result = '';
                foreach($list as $row){
                    $data = [
                        'coupon_id' => $ids,
                        'user_id' => $row->id,
                        'use_for' => 1,
                        'upstage' => 1, //代表后台发放
                        'issuance_time' => time(),  //发放时间
                        'expiration' => strtotime("+$day days", time()), //根据有优惠券天数算优惠券到期时间
                        'status' => $coupon['status'],
                        'coupon_price' => $coupon['fullminus'],
                        'man_price' => $coupon['satisfynum'],
                        'createtime' => time(),
                    ];
                    $result = \app\common\model\Couponlog::create($data);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success(__('发送成功'));
            } else {
                $this->error(__('发送失败'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


}
